﻿using System; using HISModels.ViewModel;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using KeanuMvc.Reference;
using HIS.Utils;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using HISModels.Entities;
using System.Configuration;
using HIS.Utils.Securities;
using HISModels.ViewModel;
using System.Text;

namespace HIS.Controllers.Master {
    public class ItemData : HIS.Controllers.AppBaseController {

        #region Fields
        private string strItem = string.Empty;
        private string strNotification = string.Empty;
        private Item sysItem = null;

        #endregion

        #region ItemData
        public ItemData() {
            Data.Add("Pagetitle", "Item");
            Data.Add("Notification", strNotification);
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "master-items")]
        public override void Index() {
            try {
                Data["Pagetitle"] += " :: Item List";
                RenderFile("Master\\itemdata.html");
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "master-items")]
        public void TableList() {
            try {
                string itemcode = HttpContext.Current.Request["itemcode"].NullSafeToString();
                string itemname = HttpContext.Current.Request["itemname"].NullSafeToString();
                string ssearch = "code=" + itemcode + ";nama=" + itemname;

                PostDataTablesNet pagingSearch = new PostDataTablesNet();
                pagingSearch.iDisplayLength = Convert.ToInt32(HttpContext.Current.Request["iDisplayLength"]);
                pagingSearch.iDisplayStart = Convert.ToInt32(HttpContext.Current.Request["iDisplayStart"]);
                pagingSearch.sEcho = Convert.ToInt32(HttpContext.Current.Request["sEcho"]);
                pagingSearch.sSearch = ssearch;

                string strUri = Global.ServiceUriDictionary["itempaging"] + Global.ServiceUriDictionary["requestformat"];
                StringReader stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(pagingSearch));
                string strJson = stringReader.ReadToEnd();
                stringReader.Dispose();
                base.RestService.Dispose();
                HttpContext.Current.Response.Write(strJson);
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "master-items")]
        public void EditItemData() {
            StringReader stringReader = null;
            string id = "";
            try {
                id = HttpContext.Current.Request["id"];
            } catch {
                GoToUrl("item/");
                return;
            }

            try {
                string strUri = Global.ServiceUriDictionary["item"] + id + Global.ServiceUriDictionary["requestformat"];
                stringReader = base.RestService.GetJson(strUri);
                sysItem = JsonConvert.DeserializeObject<Item>(stringReader.ReadToEnd());   
                string idChild = Convert.ToString(sysItem.ItemSubCategoryId);
                string subcategoryid = Convert.ToString(sysItem.ItemSubCategoryId);
                string shapeid = Convert.ToString(sysItem.ItemShapeId);
                Data["Pagetitle"] += " :: Edit Item";
                Data.Add("sysItem", sysItem);
                Data.Add("IsCreate", "false");
                Data.Add("Actionform", Data["rooturl"] + "master/itemdata/edititemdata/?id=" + id);
                Data.Add("ddlItemSubCategory", DropDownItemDataSubCategory(subcategoryid.NullSafeToString()));
                Data.Add("ddlItemShape", DropDownItemDataShape(shapeid.NullSafeToString()));
                Data["Notification"] = strNotification;
            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                RenderFile("Master\\edititemdata.html");
                if (stringReader != null) stringReader.Dispose();
                base.RestService.Dispose();
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "master-items")]
        public void CreateItemData() {
            StringReader stringReader = null;
            try {
                Data["Pagetitle"] += " :: Add Item";
                sysItem = new HISModels.Entities.Item();
                sysItem.CodeValue = "";
                sysItem.NameValue = "";
                Data.Add("sysItem", sysItem);
                Data.Add("ddlItemCategory", DropDownItemDataCategory(""));
                Data.Add("ddlItemSubCategory", DropDownItemDataSubCategory(""));
                Data.Add("ddlItemShape", DropDownItemDataShape(""));
                
                Data.Add("IsCreate", "true");
                Data.Add("Actionform", Data["rooturl"] + "master/itemdata/createitemdata/");
                Data["Notification"] = strNotification;

            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                RenderFile("Master\\edititemdata.html");
                if (stringReader != null) stringReader.Dispose();
                base.RestService.Dispose();
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "master-items")]
        public void DeleteItemData() {
            StringReader stringReader = null;
            string id = "";
            try {
                id = HttpContext.Current.Request["id"];
            } catch {
                GoToUrl("itemdata/");
                return;
            }

            try {
                sysItem = new HISModels.Entities.Item();
                string strUri = Global.ServiceUriDictionary["item"] + Global.ServiceUriDictionary["requestformat"];
                stringReader = base.RestService.DeleteJson(strUri, JsonConvert.SerializeObject(id));
                strNotification = JsonConvert.DeserializeObject<string>(stringReader.ReadToEnd());
                if (strNotification == string.Empty) strNotification = Helper.SuccessMessage("Data has been successfully deleted!");
                Data["Notification"] = strNotification;

            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                //RenderFile("Admins\\Actions\\editactiongroup.html");
                //stringReader.Dispose();
                //base.RestService.Dispose();


                HttpContext.Current.Response.Redirect(Data["rooturl"] + "master/itemdata");

                //GoToUrl("actiongroup/");

                base.RestService.Dispose();
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "master-items")]
        public void SaveItemDataToService() {
                    StringReader stringReader = null;
                    string strUri = string.Empty;
                    try {

                        sysItem = new Item(); Utils.Helper.SetNullToEmptyString(sysItem);
                        if (HttpContext.Current.Request["IsCreate"] != "true") {
                            string id = "";
                            try {
                                id = HttpContext.Current.Request["id"];
                            } catch { }
                            strUri = Global.ServiceUriDictionary["item"] + id + Global.ServiceUriDictionary["requestformat"];
                            ///Get Rest///
                            stringReader = base.RestService.GetJson(strUri);
                            sysItem = JsonConvert.DeserializeObject<Item>(stringReader.ReadToEnd());
                        }

                        sysItem.PostHandler<HISModels.Entities.Item>();
                        sysItem.CodeValue = sysItem.CodeValue.ReplaceSpecialChar("-").ToLower();
                        sysItem.NameValue = sysItem.NameValue.ReplaceSpecialChar("-").ToLower();
                        strUri = Global.ServiceUriDictionary["item"] + Global.ServiceUriDictionary["requestformat"];

                        if (HttpContext.Current.Request["IsCreate"] == "true") {
                            stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(sysItem));
                        } else {
                            stringReader = base.RestService.PutJson(strUri, JsonConvert.SerializeObject(sysItem));
                        }


                        sysItem = JsonConvert.DeserializeObject<Item>(stringReader.ReadToEnd());

                        if (sysItem != null) {
                            strNotification = Helper.SuccessMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                        } else {
                            strNotification = Helper.ErrorMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                        }


                        strNotification = "{\"strNotification\": \"" + strNotification + "\"}";
                        HttpContext.Current.Response.Write(strNotification);

                    } catch (Exception ex) {
                        strNotification = ex.Message;
                    } finally {

                        base.RestService.Dispose();
                    }
                }

        [HIS.Utils.Securities.Authorization(RoleAction = "master-items")]
        public string DropDownItemDataSubCategory(string selected) {
            StringBuilder returnValue = new StringBuilder();
            StringReader stringReaderDropDown = null;
            string categoryId = "";
            string strResult = string.Empty;
            string strUri = Global.ServiceUriDictionary["itemsubcategorylist"] + Global.ServiceUriDictionary["requestformat"];
            try {
                stringReaderDropDown = base.RestService.GetJson(strUri);
                List<RefItemSubCategory> listRole = JsonConvert.DeserializeObject<List<RefItemSubCategory>>(stringReaderDropDown.ReadToEnd());
                List<object[]> activeArr = new List<object[]>();
                returnValue.Append(" <select name='ItemSubCategoryId' id='ItemSubCategoryId'>  ");
                returnValue.Append("<option idParent='0' value='0'> -- Select --</option>");
                foreach (RefItemSubCategory item in listRole) {
                    if (item.Id.ToString().Equals(selected)) {
                        categoryId = Convert.ToString(item.ItemCategoryId);
                        Data.Add("ddlItemCategory", DropDownItemDataCategory(categoryId.NullSafeToString()));
                        returnValue.Append("<option idParent='" + item.ItemCategoryId + "' value='" + item.Id + "' selected='selected'>" + item.NameValue + "</option>");
                    } else {
                        
                        returnValue.Append("<option idParent='" + item.ItemCategoryId + "' value='" + item.Id + "'>" + item.NameValue + "</option>");
                    }
                }  
                returnValue.Append("</select>");
                if (selected == "") {
                    Data.Add("ddlItemCategory", DropDownItemDataCategory(categoryId.NullSafeToString()));
                }
                activeArr.Clear();
                activeArr = null;
            } catch {
            } finally {
                stringReaderDropDown.Dispose();
            }
            return returnValue.ToString();
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "master-items")]
        public string DropDownItemDataCategory(string selected) {
            StringReader stringReaderDropDown = null;
            string strResult = string.Empty;
            string strUri = Global.ServiceUriDictionary["itemcategorylist"] + Global.ServiceUriDictionary["requestformat"];
            try {
                stringReaderDropDown = base.RestService.GetJson(strUri);
                List<RefItemCategory> listRole = JsonConvert.DeserializeObject<List<RefItemCategory>>(stringReaderDropDown.ReadToEnd());
                List<object[]> activeArr = new List<object[]>();
                activeArr.Add(new object[] { "-0", "--Select--" });
                foreach (RefItemCategory item in listRole) activeArr.Add(new object[] { item.Id, item.NameValue });
                strResult = KeanuMvc.Reference.Html.DropDown("ItemRefCategoryId", string.Empty, activeArr, selected);
                activeArr.Clear();
                activeArr = null;
            } catch {
            } finally {
                stringReaderDropDown.Dispose();
            }
            return strResult;
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "master-items")]
        public string DropDownItemDataShape(string selected) {
            StringReader stringReaderDropDown = null;
            string strResult = string.Empty;
            string strUri = Global.ServiceUriDictionary["itemshapelist"] + Global.ServiceUriDictionary["requestformat"];
            try {
                stringReaderDropDown = base.RestService.GetJson(strUri);
                List<RefItemShape> listRole = JsonConvert.DeserializeObject<List<RefItemShape>>(stringReaderDropDown.ReadToEnd());
                List<object[]> activeArr = new List<object[]>();
                activeArr.Add(new object[] { "0", "--Select--" });
                foreach (RefItemShape item in listRole) activeArr.Add(new object[] { item.Id, item.NameValue });
                strResult = KeanuMvc.Reference.Html.DropDown("ItemShapeId", string.Empty, activeArr, selected);
                activeArr.Clear();
                activeArr = null;
            } catch {
            } finally {
                stringReaderDropDown.Dispose();
            }
            return strResult;
        }



        #endregion 



    }
}